package com.cloud.demo.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.cloud.demo.Handler.customerBlockHandler;
import com.demo.springcloud.entity.R;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author hxg
 * @version 1.0
 * @date 2022/1/12 16:53
 */
@RestController
public class sentinelController {
    @GetMapping("/testa")
    public String testA(){
        return "testA";
    }

    @GetMapping("/testb")
    public String testB(){
        return "testA";
    }

    @GetMapping("/testd")
    public String testD() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //int age = 10 / 0;
        return "====testD====";
    }

    @GetMapping("/byResource")
    @SentinelResource(value = "byResource",blockHandler = "dealResource")
    public R testHotKey(@RequestParam(value = "p1",required = false)String p1){
        return new R(200,"testResource"+p1);
    }

    //注意是BlockException（不要导错包）
    public R dealResource(String p1, BlockException exception){
        return new R(400,"testResource--Error"+exception.getClass().getCanonicalName()+p1);
    }

    /**
     * 按url限流
     * @return
     */
    @GetMapping("/rateLimit/byUrl")
    public R byUrl(){
        return new R(400,"testResource");
    }


    @GetMapping("/rateLimit/customBlock")
    @SentinelResource(value = "customBlock",
            //配置自定义的异常处理方法类 减少代码耦合
            blockHandlerClass = customerBlockHandler.class,
            //指定处理异常的方法
            blockHandler = "handlerException")
    public R customBlockHandler(){
        return new R(200,"customBlock");
    }

}
